package cn.zl.web.impl.devicechannel;

import cn.yunbamboos.rest.service.anno.RestServiceMapping;
import cn.yunbamboos.rest.service.dto.Page;
import cn.yunbamboos.rest.service.dto.out.BaseOutDTO;
import cn.yunbamboos.rest.service.dto.out.ErrorOutDTO;
import cn.zl.GB28181.storage.IDeviceChannelStorage;
import cn.yunbamboos.mybatis.conditions.Conditions;
import cn.zl.config.UserSettingConfig;
import cn.zl.mapper.DeviceChannelMapper;
import cn.zl.mapper.DeviceMapper;
import cn.zl.model.Device;
import cn.zl.model.DeviceChannel;
import cn.zl.web.dto.devicechannel.PlayDeviceChannelInDTO;
import cn.zl.web.dto.devicechannel.QueryDeviceChannelByPageInDTO;
import cn.zl.web.dto.devicechannel.QueryDeviceChannelByPageOutDTO;
import cn.zl.web.dto.devicechannel.PlayDeviceChannelOutDTO;
import cn.zl.web.dto.devicechannel.UpdateDeviceChannelInDTO;
import cn.zl.web.dto.devicechannel.UpdateDeviceChannelOutDTO;
import cn.zl.web.inter.devicechannel.IDeviceChannelService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;
import java.util.Optional;

@Service("DeviceChannelServiceImpl")
public class DeviceChannelServiceImpl implements IDeviceChannelService {

    private static final Logger logger = LoggerFactory.getLogger(DeviceChannelServiceImpl.class);

    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private DeviceChannelMapper deviceChannelMapper;
    @Resource
    private UserSettingConfig userSettingConfig;
    @Resource
    private IDeviceChannelStorage deviceChannelStorage;

    @RestServiceMapping(url = "/web/device-channel/queryByPage", name = "条件分页查询设备通道列表服务", in = QueryDeviceChannelByPageInDTO.class, out = QueryDeviceChannelByPageOutDTO.class)
    @Override
    public BaseOutDTO queryByPage(QueryDeviceChannelByPageInDTO in) {
        // 创建分页对象
        Page<DeviceChannel> page = new Page<>(in.getPageNo(), in.getPageSize());
        // 添加动态条件
        Conditions where = new Conditions();
        where.add("device_id", in.getDeviceId());
        // 查询总数
        int total = deviceChannelMapper.countForPage(page, where);
        // 查询当前页码数据
        List<DeviceChannel> list = deviceChannelMapper.queryForPage(page, where);
        page.setRows(list).setTotal(total);
        return new QueryDeviceChannelByPageOutDTO(page);
    }

    @RestServiceMapping(url = "/web/device-channel/update", name = "更新设备通道信息服务", in = UpdateDeviceChannelInDTO.class, out = UpdateDeviceChannelOutDTO.class)
    @Override
    public BaseOutDTO update(UpdateDeviceChannelInDTO in) {
        DeviceChannel deviceChannel = in.getDeviceChannel();
        deviceChannelMapper.update(deviceChannel);
        return new UpdateDeviceChannelOutDTO();
    }

    @RestServiceMapping(url = "/web/device-channel/play-stream", name = "播放国标设备通道服务", in = PlayDeviceChannelInDTO.class, out = PlayDeviceChannelOutDTO.class)
    @Override
    public DeferredResult<BaseOutDTO> playStream(PlayDeviceChannelInDTO in) {
        DeferredResult<BaseOutDTO> result = new DeferredResult<>(userSettingConfig.getPlayTimeout() + 10);
        Optional<Device> deviceOptional = deviceMapper.queryByPrimaryKey(in.getDeviceId());
        if (deviceOptional.isEmpty()) {
            result.setResult(ErrorOutDTO.error("设备[ {} ]未找到", in.getDeviceId()));
            return result;
        }
        Device device = deviceOptional.get();
        if (!device.isOnLine()) {
            result.setResult(ErrorOutDTO.error("设备[ {} ]不在线", in.getDeviceId()));
            return result;
        }
        Optional<DeviceChannel> channelOptional = deviceChannelMapper.queryByPrimaryKey(in.getChannelId());
        if (channelOptional.isEmpty()) {
            result.setResult(ErrorOutDTO.error("设备[ {} ]通道[ {} ]未找到", in.getDeviceId(), in.getChannelId()));
            return result;
        }
        DeviceChannel channel = channelOptional.get();
        if (!channel.isStatus()) {
            result.setResult(ErrorOutDTO.error("设备[ {} ]通道[ {} ]不在线", in.getDeviceId(), in.getChannelId()));
            return result;
        }
        // 超时响应
        result.onTimeout(() -> {
            logger.info("播放等待超时");
            result.setResult(ErrorOutDTO.error("播放超时"));
            // inviteStreamService.removeInviteInfoByDeviceAndChannel(InviteSessionType.PLAY, serial, code);
            // storager.stopPlay(serial, code);
            // 清理RTP server
        });
        deviceChannelStorage.play(device.getDeviceId(), channel.getDeviceId(), (code, msg, data) -> {

        });
        return result;
    }

}
